let crypto = require('crypto');

class StringUtil {
    constructor() {
    }

    padZero(num, cnt){
        let cntMap = {}
        if (cnt > 0){
            if (!cntMap[cnt]) {
                let str = "";
                for (let i = 0; i < cnt; i++) {
                    str += "0";
                }
                cntMap[cnt] = str;
            }
            num = (cntMap[cnt] + num).slice(-cnt);
        }
        return num;
    }

    padZeroSix(num) {
        return stringUtil.padZero(num, 6);
    }

    sha256 (str) {
        const hash = crypto.createHash('sha256');
        hash.update(str);
        return hash.digest('hex');
    }

    getSignStr(entity){
        let keyArr = [];
        for (let key in entity){
            keyArr.push(key);
        }

        keyArr.sort((str1, str2) => {
            return str1.localeCompare(str2);
        });

        let signStr = "";
        for (let i = 0; i < keyArr.length; i++) {
            let key = keyArr[i];
            // if (key !== "sign" && entity[key] && entity[key] !== "" && !this.isBlank(entity)){
            if (key !== "sign" && entity[key] && entity[key] !== ""){
                if (signStr !== ""){
                    signStr += "&";
                }
                signStr += (key + "=" + entity[key]);
            }
        }

        return signStr;
    }

    getMD5SignStr(entity){
        let keyArr = [];
        for (let key in entity){
            keyArr.push(key);
        }

        keyArr.sort((str1, str2) => {
            return str1.localeCompare(str2);
        });

        /*
        不参与签名字段
        ver
        input_charset
        sign
        sign_type
        sign_key_index
        retcode
        retmsg
        */

        let signStr = "";
        for (let i = 0; i < keyArr.length; i++) {
            let key = keyArr[i];
            if (key !== 'sign_key_index' && key !== 'retcode' && key !== 'retmsg'
             && key !== 'sign_type' && key !== "sign" && key !== 'ver' && key !== 'input_charset' 
            && entity[key] && entity[key] !== "" && !this.isBlank(entity[key])){
                if (signStr !== ""){
                    signStr += "&";
                }
                signStr += (key + "=" + entity[key]);
            }
        }

        return signStr;
    }

    isBlank(str) {
        return (!str || /^\s*$/.test(str));
    }
}


let stringUtil = new StringUtil();
module.exports = stringUtil;